/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;


/**
 *
 * @author Carlos
 */
public class mostrarUsuario extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        //Recojo la red y el user
          try{
               GestorPersistencia.crearConexion();
        }catch(ErrorConexionBD e){
                  notificarError (request, response, "Error", "Error al  conectar con la BBDD");     
                }
        
        
        SocialFP red= new SocialFP();
        /*try {
                    red.recuperaUjaenSocial();
                }catch (Exception e){
                 notificarError (request, response, "Error", "No se puede recuperar el estado de la red");
                }
        
        if (red == null) {
            notificarError (request, response, "Error", "Acceso ilegal o sesión caducada");
            return;
        }*/
        red=  (SocialFP) request.getSession ().getAttribute ("red");  
         if (red == null) {
            notificarError (request, response, "Error", "Acceso ilegal o sesión caducada");
            return;
        }
        String email=  (String) request.getSession ().getAttribute ("email");
         String clave=  (String) request.getSession ().getAttribute ("clave");
        Usuario u = red.loginUsuario(email, clave);
         if (u == null) {
            notificarError (request, response, "Error", "Acceso ilegal o sesión caducada");
            return;
        }
        
        if (!"admin".equals(u.leeEmail())){
            
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Información de Usuario</title>");
        out.println("<meta content=\"text/html; charset=utf-8\">");
       
        out.println("</head>");
        out.println("<body>");
        out.println ("<body alink=\"#000099\" bgcolor=\"#6d9fff\" link=\"#000099\" text=\"#000000\" vlink=\"#990099\" onLoad=\"setTimeout('self.location.reload()', 10000)>");
       
        // Imprimir cabecera
        out.println ("<table cellspacing=\"5\" bgcolor=\"white\" width = \"600\">");
        out.println ("<tr><td bgcolor=\"white\"><img src=\"imagenes/cabecera.jpg\" align=\"bottom\" height=\"100\" width=\"80\"></td>");
        out.println ("<td bgcolor=\"white\" align=\"left\" td valign=\"middle\"><font color=\"#f9f9f9\"><big><big><big><b>SocialFP</b></font></big></big></big></td></tr>");
        out.println ("</table>");
        
        // Imprimir información de cuenta y botón para aceptar Sol
        out.println ("<table cellspacing=\"10\" bgcolor=\"white\" width = \"600\"><tr><td>");
        out.println ("<form action=\"" + response.encodeURL ("VerSolicitudes") + "\" method=\"post\">");
        out.println ("<label for=\"email\" accesskey=\"N\">Email:    </label>");
        out.println ("<input type=\"text\" disabled name=\"email\" size=20 value=\"" + u.leeEmail()+ "\"><br>");
        out.println ("<label for=\"nombre\" accesskey=\"T\">Nombre: </label>");
        out.println ("<input type=\"text\" disabled name=\"titular\" size=20 value=\"" + u.leeNombre() + "\"><br>");
        out.println ("<label for=\"Número de Solicitudes\" accesskey=\"S\">Número de Solicitudes: </label>");
        out.println ("<input type=\"text\" disabled name=\"numsoli\" size=2 value=\"" + u.numsolicitudes() + "\">");
        out.println ("<input type=\"submit\" name=\"Aceptar\" value=\"Aceptar\" accessKey=\"S\"><br>");
        out.println ("<label for=\"descripción\" accesskey=\"S\">Descripción: </label>");
        out.println ("<input type=\"text\" disabled name=\"preferencias\" size=60 value=\"" + u.leeDescripcion() + "\">");
        out.println ("</table><br>");
        out.println ("</form></td></tr>");
        
        //Menú de botones
        out.println ("<form action=\"" + response.encodeURL ("Menu") + "\" method=\"post\">");
        out.println ("<input type=\"submit\" name=\"Buscar\" value=\"Buscar Usuarios\" accessKey=\"B\">");
        out.println ("<input type=\"submit\" name=\"VerAmigos\" value=\"Ver Amigos\" accessKey=\"A\">");
        out.println ("<input type=\"submit\" name=\"VerPrivado\" value=\"Ver Privados\" accessKey=\"S\">");
        out.println ("<input type=\"submit\" name=\"VerNotas\" value=\"Ver Notas\" accessKey=\"N\"><br>");
        out.println ("</form>");
        
        //Imprimir muro y botones para enviar mensajes
        out.println ("<table cellspacing=\"10\" bgcolor=\"white\" width = \"600\"><tr><td>");
        out.println ("<form action=\"" + response.encodeURL ("EnviarMensaje") + "\" method=\"post\">");
        out.println ("<table width = \"100%\">");
        out.println ("<caption>Mensajes muro</caption>");
        out.println ("<tr><th bgcolor=\"#e9e9e9\">Fecha</th><th bgcolor=\"#e9e9e9\">Emisor</th>");
        out.println ("<th bgcolor=\"#e9e9e9\">Contenido</th>");
        
        
        SimpleDateFormat df = new SimpleDateFormat ("dd.MM.yyyy HH:mm");
        Mensaje m;
               ArrayList lista;
               lista= new ArrayList();
               lista=(ArrayList)u.leeMensajesUsuario();
               Iterator itera = lista.listIterator();
      		  while(itera.hasNext()){
                    m=(Mensaje) itera.next();
                    out.println ("<tr>");
                    out.println ("<td bgcolor=\"#ffffff\"><small>" + df.format (m.leeFecha()) + "</small></td>");
                    out.println ("<td bgcolor=\"#ffffff\" align=\"right\"><small>" + m.leeEmisor() + "</small></td>");
                    out.println ("<td bgcolor=\"#ffffff\" align=\"right\"><small>" + m.leeContenido() + "</small></td>");
                    out.println ("</tr>");
                    
                  }
                  out.println ("</table><br>");
         out.println ("<input type=\"submit\" name=\"mensajemuro\" value=\"Mensaje Muro\" accessKey=\"M\">");
         out.println ("<input type=\"submit\" name=\"mensajeprivado\" value=\"Mensaje Privado\" accessKey=\"P\">");
         out.println ("</form></td></tr>");
         out.println ("</table>");
         
         //Botón Salir
         out.println ("<form action=\"" + response.encodeURL ("Salir") + "\" method=\"post\">");
         out.println ("<input type=\"submit\" name=\"Salir\" value=\"Salir\" accessKey=\"S\"><br>");                             
        out.println ("</form>");
       
        out.println ("</body>");
        out.println ("</html>");
        out.close();
        
        
     }else{ //Imprimimos la página de Administrador
            
            
           
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Página de Administración</title>");
        out.println("<meta content=\"text/html; charset=utf-8\">");
       
        out.println("</head>");
        out.println("<body>");
        out.println ("<body alink=\"#000099\" bgcolor=\"#6d9fff\" link=\"#000099\" text=\"#000000\" vlink=\"#990099\" onLoad=\"setTimeout('self.location.reload()', 10000)>");
       
        // Imprimir cabecera
        out.println ("<table cellspacing=\"5\" bgcolor=\"white\" width = \"600\">");
        out.println ("<tr><td bgcolor=\"white\"><img src=\"imagenes/cabecera.jpg\" align=\"bottom\" height=\"100\" width=\"80\"></td>");
        out.println ("<td bgcolor=\"white\" align=\"left\" td valign=\"middle\"><font color=\"#f9f9f9\"><big><big><big><b>SocialFP Administración</b></font></big></big></big></td></tr>");
        out.println ("</table>");
        
        //Imprimimos toda la lista de usuarios de la red para ver sus notas
       
        out.println ("<form action=\"" + response.encodeURL ("VerNotas") + "\" method=\"post\">");
        
                  //out.println ("<label for=\"Destinatario\" accesskey=\"D\">Destinatario: </label>");
                  //out.println("<input type=\"text\" name=\"email\" size=10><br><br>");
        out.println("<b><big>Selecciona el usuario para ver sus calificaciones</big></b><br>");

        out.println ("<select name=\"Usuario\" multiple=\"multiple\">");
       
        ArrayList lista;
        Usuario temp;
        lista= new ArrayList();
        lista=(ArrayList)red.todosUsuarios();
        Iterator itera = lista.listIterator();
      	while(itera.hasNext()){
            
                
            temp=(Usuario) itera.next();
            if (temp.leeEmail().equals(u.leeEmail())){
                
            }else{
            out.println ("<option value="+temp.leeEmail()+">"+temp.leeNombre()+" ("+temp.leeEmail()+")"+"</option>");
            }
        }
       
        out.println ("</select><br>");
        out.println ("<input type=\"submit\" name=\"Aceptar\" value=\"Aceptar\" accessKey=\"A\">"); 
        out.println ("</form></td></tr>");
        
        
        //Imprimimos la lista de asignaturas 
        out.println ("<form action=\"" + response.encodeURL ("PonNotas") + "\" method=\"post\">");
        out.println("<b><big>Selecciona el módulo a calificar</big></b><br>");

        out.println ("<select name=\"Modulo\" multiple=\"multiple\">");
       
        
        out.println ("<option value=redes>Redes</option>");
        out.println ("<option value=hardware>Hardware</option>");
        out.println ("</select><br>");
        out.println ("<input type=\"submit\" name=\"Aceptar\" value=\"Aceptar\" accessKey=\"A\">"); 
        out.println ("</form></td></tr>");
         
         //Botón Salir
         out.println ("<form action=\"" + response.encodeURL ("Salir") + "\" method=\"post\">");
         out.println ("<input type=\"submit\" name=\"Salir\" value=\"Salir\" accessKey=\"S\"><br>");                             
        out.println ("</form>");
       
        out.println ("</body>");
        out.println ("</html>");
        out.close(); 
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    protected void notificarError (HttpServletRequest request, HttpServletResponse response, String cabecera, String descripcion) 
        throws ServletException, IOException
    {
        RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp?cabecera=" + cabecera 
                + "&descripcion=" + descripcion + "&continuar=mostrarUsuario");
        dispatcher.forward (request, response);    
    }    

    @Override
    public String getServletInfo() {
        return "Mostrar la información y últimos movimientos de la cuenta";
    }
    
}
